<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="C++,Python,语法,">










<meta name="description" content="这篇文章主要意图是借C++作用域规则引出Python的LEGB规则，同时带有一些我对于跨语言学习的想法。  首先提一个问题，作用域是什么？  标准解释为：限定一个名字的可用性代码范围就是这个名字的作用域。简单来说其实就是一个变量从创建到销毁的范围。  那么下一个问题？作用域有哪些？  大部分同学可能会说作用域分局部和全全局啊，局部优先局部，全局只能用全局。是的，从我们大部分人第一个学习的语言——C">
<meta name="keywords" content="C++,Python,语法">
<meta property="og:type" content="article">
<meta property="og:title" content="CPP与Python的作用域规则比较">
<meta property="og:url" content="https://yujunjiex.gitee.io/2019/03/11/CPP与Python的作用域规则比较/index.html">
<meta property="og:site_name" content="Yu&#39;s Home">
<meta property="og:description" content="这篇文章主要意图是借C++作用域规则引出Python的LEGB规则，同时带有一些我对于跨语言学习的想法。  首先提一个问题，作用域是什么？  标准解释为：限定一个名字的可用性代码范围就是这个名字的作用域。简单来说其实就是一个变量从创建到销毁的范围。  那么下一个问题？作用域有哪些？  大部分同学可能会说作用域分局部和全全局啊，局部优先局部，全局只能用全局。是的，从我们大部分人第一个学习的语言——C">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2023-02-23T12:31:14.830Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="CPP与Python的作用域规则比较">
<meta name="twitter:description" content="这篇文章主要意图是借C++作用域规则引出Python的LEGB规则，同时带有一些我对于跨语言学习的想法。  首先提一个问题，作用域是什么？  标准解释为：限定一个名字的可用性代码范围就是这个名字的作用域。简单来说其实就是一个变量从创建到销毁的范围。  那么下一个问题？作用域有哪些？  大部分同学可能会说作用域分局部和全全局啊，局部优先局部，全局只能用全局。是的，从我们大部分人第一个学习的语言——C">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '9PFXHHRD2G',
      apiKey: '45293228d8a5cecc1c0826fb3d34a130',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"没有找到任何结果: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://yujunjiex.gitee.io/2019/03/11/CPP与Python的作用域规则比较/">





  <title>CPP与Python的作用域规则比较 | Yu's Home</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1746d8de4fb78edd21f9004d348fa6be";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Yu's Home</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">管它真理无穷</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于Yu
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yujunjiex.gitee.io/2019/03/11/CPP与Python的作用域规则比较/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Yu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/xiaomai.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Yu's Home">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">CPP与Python的作用域规则比较</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-11T17:29:42+08:00">
                2019-03-11
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
              <i class="fa fa-comment-o"></i>
              </span>
              <a href="/2019/03/11/CPP与Python的作用域规则比较/#comments" itemprop="discussionUrl">
              <span class="post-comments-count valine-comment-count" data-xid="/2019/03/11/CPP与Python的作用域规则比较/" itemprop="commentCount"></span>
              </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,715
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>这篇文章主要意图是借C++作用域规则引出Python的LEGB规则，同时带有一些我对于跨语言学习的想法。</p>
<blockquote>
<p>首先提一个问题，作用域是什么？</p>
</blockquote>
<p>标准解释为：<strong>限定一个名字的可用性代码范围就是这个名字的作用域。</strong>简单来说其实就是一个变量从创建到销毁的范围。</p>
<blockquote>
<p>那么下一个问题？作用域有哪些？</p>
</blockquote>
<p>大部分同学可能会说作用域分局部和全全局啊，局部优先局部，全局只能用全局。是的，从我们大部分人第一个学习的语言——C语言来说，的确就这两个。但是现如今的语言，就拿离C最近的C++来讲，作用域规则都是存在不同的。下面具体说明。</p>
<a id="more"></a> 

<h2 id="C-作用域"><a href="#C-作用域" class="headerlink" title="C++作用域"></a>C++作用域</h2><p>C++的作用域大致可分为下面几种，可能有疏漏，但大体如此：</p>
<p><strong>1.函数原型作用域：</strong></p>
<p>此作用域为c++程序中最小的作用域，生存周期最短。</p>
<p>例：int func（int i） i为参数，作用域类型为函数原型类型。</p>
<p><strong>2.块作用域（局部作用域）</strong>：与C语言类似；</p>
<p>函数体或某一个模块中变量，从声明开始，到块终止时结束，例如函数，循环内声明的变量</p>
<p><strong>3.静态变量作用域（局部或全局）</strong></p>
<p><strong>4.类的作用域</strong></p>
<p>类中的数据和函数分为公有类（public），保护类（protected），私有类（private）</p>
<p>具体的规则与面向对象设计有关，这里不多提</p>
<p><strong>5.命名空间作用域</strong></p>
<p>namespace 命名空间名{</p>
<p>各种声明（class的声明，函数的声明，变量的声明，常量的声明………）}</p>
<p>这个概念在C中是没有的。名字空间的提出是为了解决C模块间的同名变量冲突的问题。所以里面的变量也属于全局的，但是加上了限定名。引用方式：<strong>命名空间名::标识符名</strong></p>
<h2 id="一个小建议"><a href="#一个小建议" class="headerlink" title="一个小建议"></a>一个小建议</h2><p>下面在介绍python的LEGB规则的时候，我想先给看到这篇文章的同学一个建议，也是我之前犯过的一个错误。对于程序员来说，通常首先学的C语言然后学的C++，老师上课时可能时常作比较，让我们更好的上手学习。所以我们可能会有这样一个想法：语言都这么相近，多多对比也就学会了。其实我认为这个想法不全对甚至有的时候是很错误的！就拿C和最近最相似的C++来说，C为什么没有命名空间？C为什么没有函数重载？</p>
<p>C/C++这么相近的语言都有各种设计上的不同，那何况是动态比静态，编译比解释，强比弱。。</p>
<p>所以我建议大家不要完美主义。像一些语言设计上的不同最好不要太深入，能够快速切换到另一门语言的逻辑上才是最主要最应该掌握的技能！总结来说就是一句话：<strong>可以，但没有必要！</strong></p>
<h2 id="Python的LEGB规则"><a href="#Python的LEGB规则" class="headerlink" title="Python的LEGB规则"></a>Python的LEGB规则</h2><p>还记得之前说的C++的命名空间吗？其实命名空间这个概念是脱离于语言的，很多语言都有这个设计。</p>
<p><strong>那么python中命名空间的规则是什么样的呢？</strong></p>
<p>​    <strong>python中一切皆对象</strong>，所以python中的变量名是字符串来表示的。</p>
<p>例如:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="number">10</span></span><br></pre></td></tr></table></figure>

<p>表示建立<em>字符串对象</em><code>a</code>与<em>Number</em>对象<code>10</code>之间的对应关系。由于这是一种<strong>映射关系</strong>，所以，可以使用<strong>键-值</strong>的形式来表示，即<strong>{name : object}</strong>。<br>前面已经说过，<strong>命名空间是对变量名的分组划分</strong>，所以，Python的命名空间就是对许多<strong>键-值</strong>对的分组划分，即，<strong>键值对的集合</strong>，因此：</p>
<blockquote>
<p>Python的命名空间是一个字典，字典内保存了变量名称与对象之间的映射关系</p>
</blockquote>
<p><strong>Tips：</strong>python中有两个内置函数locals()和globals()用于分别打印当前模块的局部和全局的命名空间（就是个字典）</p>
<p>下面列出python的作用域规则，简称为<strong>LEGB</strong>，很简单</p>
<blockquote>
<p><strong>LEGB含义解释：</strong><br>L-Local(function)；函数内的名字空间<br>E-Enclosing function locals；外部嵌套函数的名字空间(例如closure)<br>G-Global(module)；函数定义所在模块（文件）的名字空间<br>B-Builtin(Python)；Python内置模块的名字空间</p>
</blockquote>
<p><strong>LEGB就是用来规定命名空间查找顺序的规则</strong>。</p>
<blockquote>
<p>LEGB规定了查找一个名称的顺序为：local–&gt;enclosing function locals–&gt;global–&gt;builtin</p>
</blockquote>
<p>举个栗子来说明：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"><span class="comment"># encoding: utf-8</span></span><br><span class="line"></span><br><span class="line">x = <span class="number">1</span> </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">foo</span><span class="params">()</span>:</span></span><br><span class="line">    x = <span class="number">2</span> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">innerfoo</span><span class="params">()</span>:</span></span><br><span class="line">        x = <span class="number">3</span> </span><br><span class="line">        <span class="keyword">print</span> <span class="string">'locals '</span>, x</span><br><span class="line">    innerfoo()</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'enclosing function locals '</span>, x</span><br><span class="line"></span><br><span class="line">foo()</span><br><span class="line"><span class="keyword">print</span> <span class="string">'global '</span>, x</span><br></pre></td></tr></table></figure>

<p>运行结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">locals  <span class="number">3</span></span><br><span class="line">enclosing function locals  <span class="number">2</span></span><br><span class="line"><span class="keyword">global</span>  <span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>下面将Python与C++的作用域规则对比理解试一下：</p>
<p>我个人认为python与C++在作用域上的最大区别就是块作用域的区别。python中是没有块作用域的，比如很多人在python中使用的第一个循环语句：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">    print(i)</span><br></pre></td></tr></table></figure>

<p>大家是不是认为这类比C++或Java等语言的话就是下面这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;<span class="number">10</span>; i++)&#123;</span><br><span class="line">    System.out.println(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>的确这两个运行的结果是一样的，但是最大的区别是：java中的变量i在循环结束后是被销毁的，因为超出了自己的作用域。而python的话i还是在它所归属的函数或模块的作用域内，比如将语句做一个更改：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">	print(i)</span><br><span class="line">print(i)	<span class="comment"># 结果是9</span></span><br></pre></td></tr></table></figure>

<p>有人可能会问了，C++中有类作用域，命名空间作用域，而python只有模块作用域和内置模块作用域啊？</p>
<p>其实你可以把python中的函数+外部嵌套函数作用域应用到类作用域上是一样的，模块作用域其实可以类比全局作用域。而C++中的命名空间作用域在python中已经实现了，python不允许直接调用其他模块的名字空间，要加上<strong>文件名.变量</strong>才可以访问到，也就不存在不同模块间重名的问题了。</p>
<p>还有关于内置模块，python可以直接使用print(),help()这样的方法，而C++中并没有内置模块吧，而且C++中的内置变量是不能作为变量名的。</p>
<p>上面的对比除了块作用域的话，其他都有强答的嫌疑 2333…  所以说语言特性间的对比意义不大，只要能熟悉各个语言的特点，快速开发才是根本。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>觉得好的话就打赏Ta一瓶冰阔落吧</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Yu 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Yu 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Yu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://yujunjiex.gitee.io/2019/03/11/CPP与Python的作用域规则比较/" title="CPP与Python的作用域规则比较">https://yujunjiex.gitee.io/2019/03/11/CPP与Python的作用域规则比较/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C/" rel="tag"># C++</a>
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/语法/" rel="tag"># 语法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/31/谈谈计算机中的编码问题/" rel="next" title="谈谈计算机中的编码问题">
                <i class="fa fa-chevron-left"></i> 谈谈计算机中的编码问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/11/python中的实例方法，类方法，静态方法/" rel="prev" title="python中的实例方法，类方法，静态方法">
                python中的实例方法，类方法，静态方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5b03d4a278f58ab9" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/xiaomai.png" alt="Yu">
            
              <p class="site-author-name" itemprop="name">Yu</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yujunjiex" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#C-作用域"><span class="nav-number">1.</span> <span class="nav-text">C++作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一个小建议"><span class="nav-number">2.</span> <span class="nav-text">一个小建议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python的LEGB规则"><span class="nav-number">3.</span> <span class="nav-text">Python的LEGB规则</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heartbeat"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Yu</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">46.7k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a></div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>

<script type="text/javascript" src="/custom/fold_action.js?v="></script>





  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//code.bdstatic.com/npm/leancloud-storage@4.12.0/dist/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'rg0EMRYKYKMhOh1zwqEKS5jz-gzGzoHsz',
        appKey: 'T04zQc0OzQd1uxOqcVomoGqj',
        placeholder: '(= =)~*只有10086嘘寒问暖',
        avatar:'mm',
        guest_info:guest,
        pageSize:'5' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  


  

  

  
  

  

  

  


</body>
</html>

